package com.wuhainan.beelzebub.service.system;

import com.wuhainan.beelzebub.common.BaseService;
import com.wuhainan.beelzebub.entity.system.Position;
import com.wuhainan.beelzebub.repository.system.PositionRepository;
import com.wuhainan.beelzebub.utils.PageInfo;
import com.wuhainan.beelzebub.utils.TableData;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <br>Created by 吴海南 on 2017-12-18.
 * <br>星期一 at 下午 3:05.
 */
@Service
public class PositionService extends BaseService<Position>{
    @Resource
    private PositionRepository repository;
    public List<Position> findAll() {
        Sort sort=new Sort(Sort.Direction.ASC,"code");
        return repository.findAll(sort);
    }

    public TableData findPositionPage(PageInfo pageInfo, Position position) {
        Page<Position> page=repository.findAll((root, cq, cb) -> {
            search(position, cq, cb, root);//模糊查询
            return cq.getRestriction();
        },pageable(pageInfo,sort(pageInfo, Sort.Direction.ASC,"code")));
        return tableData(page);
    }
    public Position findPositionById(String id) {
        return repository.findOne(id);
    }

    /**
     * 保存职位
     *
     * @param position 职位
     */
    public void savePosition(Position position) {
        if(null==position.getCode()){
            Integer maxCode=maxCode();
            if (null==maxCode){
                maxCode=0;
            }
            position.setCode(maxCode+1);
        }
        repository.save(position);
    }

    /**
     * 删除职位
     *
     * @param position 职位
     */
    public void deletePosition(Position position) {
        repository.delete(position);
    }
    /**
     * 查询最大code
     * @return maxCode
     */
    public Integer maxCode() {
        return repository.maxCode();
    }
    
}
